package com.softer.wxzj.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softer.wxzj.common.entity.CommonResult;
import com.softer.wxzj.common.entity.Page;
import com.softer.wxzj.common.enums.MessageEnum;
import com.softer.wxzj.common.enums.NumStrEnum;
import com.softer.wxzj.common.enums.NumberEnum;
import com.softer.wxzj.common.enums.ShiroResultEnum;
import com.softer.wxzj.common.error.CourseException;
import com.softer.wxzj.common.flow.enums.FlowStateEnum;
import com.softer.wxzj.common.flow.enums.FlowTypeEnum;
import com.softer.wxzj.common.flow.util.FlowAddAuditUtil;
import com.softer.wxzj.common.logic.CalculateAmount;
import com.softer.wxzj.common.util.*;
import com.softer.wxzj.entity.*;
import com.softer.wxzj.mapper.*;
import com.softer.wxzj.service.BaseHouseInfoService;
import com.softer.wxzj.service.BaseOwnerInfoService;
import com.softer.wxzj.service.DepReqListInfoService;
import lombok.var;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author ludexing
 */
@Service
public class DepReqListInfoServiceImpl implements DepReqListInfoService {
    @Autowired
    private SysCoreParamMapper sysCoreParamMapper;
    @Autowired
    private DepReqListInfoMapper depReqListInfoMapper;
    @Autowired
    private BaseRegionInfoMapper baseRegionInfoMapper;
    @Autowired
    private BaseHouseInfoMapper baseHouseInfoMapper;
    @Autowired
    private BaseBuildInfoMapper baseBuildInfoMapper;
    @Autowired
    private ZoneCodeMapper zoneCodeMapper;
    @Autowired
    private FlowAddAuditUtil flowAddAuditUtil;
    @Autowired
    private BaseOwnerInfoMapper baseOwnerInfoMapper;
    @Autowired
    private CalculateAmount calculateAmount;
    @Autowired
    private OperUtil zoneCodeUtil;
    @Autowired
    private DepModeInfoMapper depModeInfoMapper;
    @Autowired
    private FlowInstanceMapper flowInstanceMapper;
    @Autowired
    private AccTransactionLogMapper accTransactionLogMapper;
    @Autowired
    private FileServiceImpl fileService;
    @Autowired
    private BaseHouseInfoService baseHouseInfoService;
    @Autowired
    private BaseOrganizationMapper baseOrganizationMapper;
    @Autowired
    private BaseOwnerInfoService baseOwnerInfoService;
    @Autowired
    private AccKeepAccountMapper accKeepAccountMapper;
    @Autowired
    private DepReqMapper depReqMapper;
    @Autowired
    private DepositApplyServiceImpl depositApplyService;

    /**
     * 两个查询
     *
     * @param page
     * @param depReqListInfo
     * @param fuzzy
     * @return
     */
    @Override
    public PageInfo<DepReqListInfo> getDepReqListInfoList(Page page, DepReqListInfo depReqListInfo, String fuzzy) {
        depReqListInfo.setZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<DepReqListInfo> list = depReqListInfoMapper.findList(fuzzy, depReqListInfo);
        DepReqListInfo depPage = pageDep(list);
        DepReqListInfo depAll = depReqListInfoMapper.findListAll(fuzzy, depReqListInfo);

        list.add(depPage);
        list.add(depAll);
        return new PageInfo<>(list);
    }

    @Override
    public PageInfo<DepReqListInfo> getDepReqListInfoListPrint(Page page, DepReqListInfo depReqListInfo, String fuzzy) {
        depReqListInfo.setZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<DepReqListInfo> list = depReqListInfoMapper.findListPrint(fuzzy, depReqListInfo);
        DepReqListInfo depPage = pageDep(list);
        DepReqListInfo depAll = depReqListInfoMapper.findListAllPage(fuzzy, depReqListInfo);
        list.add(depPage);
        list.add(depAll);
        return new PageInfo<>(list);
    }

    /**
     * 分页合计
     *
     * @param list
     * @return
     */
    private DepReqListInfo pageDep(List<DepReqListInfo> list) {
        DepReqListInfo depPage = new DepReqListInfo();
        if (null == depPage.getStruArea()) {
            depPage.setStruArea(BigDecimal.ZERO);
        }
        if (null == depPage.getPayAmount()) {
            depPage.setPayAmount(BigDecimal.ZERO);
        }
        if (null == depPage.getDeferAccr()) {
            depPage.setDeferAccr(BigDecimal.ZERO);
        }
        if (null == depPage.getDueAmount()) {
            depPage.setDueAmount(BigDecimal.ZERO);
        }
        for (DepReqListInfo d : list) {
            if (null != d.getStruArea()) {
                depPage.setStruArea(depPage.getStruArea().add(d.getStruArea()));
            }
            if (null != d.getPayAmount()) {
                depPage.setPayAmount(depPage.getPayAmount().add(d.getPayAmount()));
            }
            if (null != d.getDueAmount()) {
                depPage.setDueAmount(depPage.getDueAmount().add(d.getDueAmount()));
            }
            if (null != d.getDeferAccr()) {
                depPage.setDeferAccr(depPage.getDeferAccr().add(d.getDeferAccr()));
            }
        }
        return depPage;
    }

    /**
     * 撤销查询 列表
     *
     * @param page
     * @param depositApply
     * @param fuzzy
     * @return
     */
    @Override
    public PageInfo<List<Map>> findRevocationList(Page page, DepositApply depositApply, String fuzzy) {
        depositApply.setZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<DepositApply> list = depReqListInfoMapper.findRevocationList(depositApply, fuzzy);
        for (DepositApply d : list) {
            if ((NumStrEnum.TWO.getNum()).equals(d.getType())) {
                DepReqListInfo depReqListInfo = depReqListInfoMapper.getInfo(d.getBusinessId());
                d.setDepDate(depReqListInfo.getCreateTime());
                d.setNo(null);
                d.setValidDate(d.getDepListDate());
                d.setTotalNum(1);
                d.setTotalAmount(d.getTotalAmount());
            }
        }
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * 撤销查询 列表
     *
     * @param page
     * @return
     */
    @Override
    public PageInfo<DepReq> findRevocationListDep(Page page, DepReq depReq) {
        depReq.setZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<DepReq> list = depReqListInfoMapper.findRevocationListDep(depReq);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

    /**
     * 撤销查看
     *
     * @param id 撤销ID
     * @return 详情
     */
    @Override
    public PageInfo<DepositAudit> getRevocationInfo(Page page, String id) {
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<DepositAudit> list = depReqListInfoMapper.getRevocationInfo(id);
        if (list != null) {
            return new PageInfo(list);
        }

        return new PageInfo();
    }

    @Override
    public PageInfo<List<Map>> getHouseListByBuilIds(Page page, String buildIds) {
        List<Map> mapList = new ArrayList<>();
        String[] ids = buildIds.split(",");
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getHouseListByBuilIds(ids);
        PageInfo pageInfo = new PageInfo(list);
        String changeDep = NumStrEnum.ONE.getNum();
        for (BaseHouseInfo baseHouseInfo : list) {
            int no = flowInstanceMapper.selectChangeHouseAndOwner(baseHouseInfo.getId(), "base_house_info_update");
            BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.selectOwner(baseHouseInfo.getId());
            int nu = 0;
            if (null == baseOwnerInfo) {
                nu = 0;
            } else {
                nu = flowInstanceMapper.selectChangeHouseAndOwner(baseOwnerInfo.getId(), "base_owner_info_update");
            }
            if (no != 0 && nu == 0) {
                baseHouseInfo.setChange(NumStrEnum.ZERO.getNum());
            } else {
                baseHouseInfo.setChange(NumStrEnum.ONE.getNum());
            }
            BigDecimal dueAmount = BigDecimal.ZERO;
            DepModeInfo depModeInfo = depModeInfoMapper.getInfo(baseHouseInfo.getFirstMode());
            if (null == depModeInfo) {
                dueAmount = null;
            } else if (null == depModeInfo.getDepType()) {
                dueAmount = null;
            } else if ((NumStrEnum.ONE.getNum()).equals(depModeInfo.getDepType())) {
                if (null == baseHouseInfo.getPrice()) {
                    dueAmount = null;
                } else {
                    dueAmount = getDueAmount(baseHouseInfo);
                }
            } else {
                dueAmount = getDueAmount(baseHouseInfo);
            }
            Map<String, Object> map = new HashMap(6);
            //封装的  实体
            map.put("house", baseHouseInfo);
            if ((NumStrEnum.ZERO.getNum()).equals(baseHouseInfo.getChange())) {
                changeDep = NumStrEnum.ZERO.getNum();
            }
            //应缴金额
            map.put("dueAmount", dueAmount);
            //自动填充 实付金额
            map.put("payAmount", dueAmount);
            mapList.add(map);
        }
        if (0 != mapList.size()) {
            mapList.get(0).put("changeDep", changeDep);
        }

        pageInfo.setList(mapList);

        return pageInfo;
    }

    /**
     * 根据房屋ID查询交存详情
     *
     * @param id 房屋ID
     * @return 交存详情
     */
    @Override
    public Map getDepositByHouseId(String id, String lid) {
        Map<String, Object> map = new HashMap<>(16);
        BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.selectOwner(id);
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(id);
        BigDecimal dueAmount = getDueAmount(baseHouseInfo);
        if (null == dueAmount) {
            dueAmount = BigDecimal.ZERO;
        }
        map.put("id", id);
        int no = 0;
        //参数设置
        String param = sysCoreParamMapper.getParamValueByCode("14");
        if (StringUtils.isNotBlank(param)) {
            if ((NumStrEnum.ONE.getNum()).equals(param)) {
                //查询是不是第一次交存
                // int frequency = depReqMapper.selectHouseFirstFunbal(id);
                int frequency = accTransactionLogMapper.selectByOwnerId(id);
                if (frequency > 0) {
                    no = 1;
                }
            }
        }
        //参数设置，最低不能少于多少钱
        String money = sysCoreParamMapper.getParamValueByCode("11");
        map.put("dueAmount", dueAmount);
        map.put("no", no);
        map.put("ownerName", baseOwnerInfo == null ? "" : baseOwnerInfo.getName());
        map.put("houseSite", baseHouseInfo.getHouseSite());
        map.put("struArea", baseHouseInfo.getStruArea());
        map.put("firstMode", baseHouseInfo.getFirstMode());
        map.put("dueState", baseHouseInfo.getDueState());
        map.put("payAmount", null);
        map.put("money", money);
        if (null != baseOwnerInfo) {
            map.put("ownerNo", baseOwnerInfo.getId());
        } else {
            map.put("ownerNo", null);
        }

        String depDate = DateUtils.getDateNow();
        //        if (StringUtils.isNotBlank(lid)) {
//            depDate = depReqListInfoMapper.getInfo(lid).getDepDate();
//            if (null != depReqListInfoMapper.getInfo(lid).getPayAmount()) {
//                map.put("payAmount", depReqListInfoMapper.getInfo(lid).getPayAmount());
//            }
//        }
        map.put("depDate", depDate);
        return map;
    }

    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult saveDepReqListInfos(List<DepReqListInfo> list) {
        for (DepReqListInfo depReqListInfo : list) {
            String id = save(depReqListInfo);
            if (StringUtils.isBlank(id)) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        }
        return CommonResult.ResponseResult(1);
    }

    @Override
    public CommonResult selectCount(String id) {
        int num = depReqListInfoMapper.selectCount(id);
        if (num > 0) {
            return CommonResult.ResponseResult(201, "该房屋发生过交存，请在变更中修改信息");
        }
        return CommonResult.ResponseResult(200, "操作成功");
    }

    /**
     * 计算应缴金额
     *
     * @param baseHouseInfo
     * @return
     */
    public BigDecimal getDueAmount(BaseHouseInfo baseHouseInfo) {
        BigDecimal dueAmount;
        //初教应缴金额
        BigDecimal bigDecimal = calculateAmount.calculateDueAmount(baseHouseInfo);
        if (bigDecimal == null) {
            dueAmount = BigDecimal.ZERO;
        } else {
            //计算已经交存的金额
            BigDecimal outMoney = accTransactionLogMapper.selectMoneyReqAll(baseHouseInfo.getId());
            BigDecimal inMoney = accTransactionLogMapper.selectMoneyDepAll(baseHouseInfo.getId());
            BigDecimal money = inMoney.subtract(outMoney);
            //本次应缴金额
            dueAmount = money == null ? bigDecimal : bigDecimal.subtract(money);
        }
        return dueAmount;
    }

    @Override
    @Deprecated
    public CommonResult insert(DepReqListInfo info) {
        CommonResult commonResult;
        info.setId(UUIDUtil.getUUID());
        info.setCreater(ShiroUserUtil.getUserName());
        info.setCreateTime(DateUtils.getNow());
        info.setState(NumStrEnum.ONE.getNum());
        //add  默认  维护成功  状态 1
        var ret = depReqListInfoMapper.insert(info);
        if (ret > 0) {
            commonResult = CommonResult.ResponseResult(ret);
        } else {
            commonResult = CommonResult.ResponseResult(ret, "缴存失败");
        }
        return commonResult;
    }

    @Override
    @Deprecated
    public CommonResult update(DepReqListInfo depReqListInfo) {
        CommonResult commonResult;
        depReqListInfo.setModifier(ShiroUserUtil.getUserName());
        depReqListInfo.setUpdateTime(DateUtils.getNow());
        var ret = depReqListInfoMapper.update(depReqListInfo);
        if (ret > 0) {
            commonResult = CommonResult.ResponseResult(ret);
        } else {
            commonResult = CommonResult.ResponseResult(ret, "缴存失败");
        }
        return commonResult;
    }


    @Override
    @Deprecated
    public CommonResult delete(String id) {
        return null;
    }

    @Override
    public PageInfo<DepReqListInfo> getList(Page page, DepReqListInfo depReqListInfo) {
        return null;
    }

    @Override
    public DepReqListInfo getInfo(String id) {
        return null;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String save(DepReqListInfo info) {
        if (info == null) {
            return null;
        }
        BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(info.getHouseId());
        //房屋状态
        baseHouseInfoService.houseState(baseHouseInfo);
        int no = depReqListInfoMapper.selecthouseDep(info.getHouseId(), info.getOwnerNo());
        if (no > 0) {
            return null;
        }
        if (FlowTypeEnum.DEPOSIT.getType().equals(baseHouseInfo.getFlowInProgress())) {
            return null;
        }
        if (baseHouseInfo.getDueState().equals(NumStrEnum.ONE.getNum()) || baseHouseInfo.getDueState().equals(NumStrEnum.TWO.getNum())) {
            return null;
        }
        /**
         * 添加房屋状态
         */
        baseHouseInfo.setFlowInProgress(FlowTypeEnum.DEPOSIT.getType());
        int num = baseHouseInfoMapper.update(baseHouseInfo);
        if (num == 0) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        info.setBuildId(baseHouseInfo.getBuildNo());
        info.setDepModeId(baseHouseInfo.getFirstMode());
            /*
            若 该条维护 属于 add
                判断审批流   如果 flowState判定为 2  通过，则 state=2  表示可以 绑定申请
             */
        var id = UUIDUtil.getUUID();
        info.setId(id);
        info.setCreater(ShiroUserUtil.getUserName());
        String flowState = flowAddAuditUtil.initFlow(id, FlowTypeEnum.DEPOSIT.getType(), null);
        if ((NumStrEnum.TWO.getNum()).equals(flowState)) {
            info.setRecDate(DateUtils.getDateNow());
        }
        info.setFlowState(flowState);
        info.setState(flowState != null && flowState.equals(NumStrEnum.TWO.getNum()) ? NumStrEnum.TWO.getNum() : NumStrEnum.ONE.getNum());
        //初交
        info.setDepType(NumStrEnum.ONE.getNum());
        depReqListInfoMapper.insert(info);
        //保存图片
        CommonResult commonResult = fileService.addFile(info.getFileTypeList(), id);
        if (ShiroResultEnum.FAIL.getCode() == commonResult.getData()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), commonResult.getMessage());
        }
        return info.getId();
    }


    /**
     * 缴存维护 两个查询  小区
     *
     * @param page  分页实体
     * @param fuzzy 模糊查询字段
     * @param info  查询实体 regionName 小区名称
     *              regionNo 小区编号
     *              address 地址
     * @return 待维护小区列表
     */
    @Override
    public PageInfo<List<Map>> getRegionInfoList(Page page, String fuzzy, BaseRegionInfo info) {
        List<Map> mapList = new ArrayList<>();
        info.setLoginZoneCode(zoneCodeUtil.getZoneCode());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseRegionInfo> list = baseRegionInfoMapper.findList(info, fuzzy);
        PageInfo pageInfo = new PageInfo(list);
        list.forEach(x -> {
            x.setZoneCode(zoneCodeMapper.getZoneName(x.getZoneCode()));
            //查询总户数
            int houseCount = baseHouseInfoMapper.getCountByRegionId(x.getId(), null);
            //查询足额户数
            int fullHouseCount = baseHouseInfoMapper.getCountByRegionId(x.getId(), "1,2");
            //续交户数
            int depDevelopNum = baseHouseInfoMapper.getDepDevelopNum(x.getId(), null);
            if (houseCount == fullHouseCount) {
                x.setNum(1);
            } else {
                x.setNum(0);
            }
            int shouldHouseCount = houseCount - fullHouseCount;
            Map<String, Object> map = new HashMap(6);
            //封装的 小区 实体
            map.put("region", x);
            //总户数  房间数
            map.put("houseCount", houseCount);
            //足额交存 户数
            map.put("fullHouseCount", fullHouseCount);
            //应交户数
            map.put("shouldHouseCount", shouldHouseCount);
            //续交户数
            map.put("depDevelopNum", depDevelopNum);
            mapList.add(map);
        });
        pageInfo.setList(mapList);
        return pageInfo;
    }

    @Override
    public PageInfo<List<Map>> getBiuldList(Page page, BaseBuildInfo baseBuildInfo) {
        List<Map> mapList = new ArrayList<>();
        baseBuildInfo.setFlowState(NumStrEnum.TWO.getNum());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseBuildInfo> list = baseBuildInfoMapper.findList(baseBuildInfo);
        //排序
        // baseBuildInfoService.reorder(list);
        PageInfo pageInfo = new PageInfo(list);
        list.forEach(x -> {
            int houseCount = baseHouseInfoMapper.getCountByBuildId(x.getId(), null);
            int fullHouseCount = baseHouseInfoMapper.getCountByBuildId(x.getId(), "1,2");
            int depDevelopNum = baseHouseInfoMapper.getDepDevelopNum(null, x.getId());
            int shouldHouseCount = houseCount - fullHouseCount;
            if (houseCount == fullHouseCount) {
                x.setNum(0);
            } else {
                x.setNum(1);
            }
            Map<String, Object> map = new HashMap();
            //封装的 小区 实体
            map.put("build", x);
            //总户数  房间数
            map.put("houseCount", houseCount);
            //足额 户数
            map.put("fullHouseCount", fullHouseCount);
            //未足额户数
            map.put("shouldHouseCount", shouldHouseCount);
            //续交户数
            map.put("depDevelopNum",depDevelopNum);
            mapList.add(map);
        });
        pageInfo.setList(mapList);
        return pageInfo;
    }

    @Override
    public PageInfo<List<Map>> getHouseList(Page page, BaseHouseInfo info) {
        List<Map> mapList = new ArrayList<>();
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.findList(info);
        BaseHouseInfo pageBase = new BaseHouseInfo();
        BaseHouseInfo baseAll = new BaseHouseInfo();
        //分页
        Map<String, Object> pageMap = new HashMap(2);
        Map<String, Object> allMap = new HashMap(2);
        BigDecimal pageAmount = BigDecimal.ZERO;
        BigDecimal allAmount = BigDecimal.ZERO;
        PageInfo pageInfo = new PageInfo(list);
        for (BaseHouseInfo x : list) {
            BigDecimal dueAmount = BigDecimal.ZERO;
//            x.setHouseSite(x.getHouseSite()+"("+x.getDicName()+")");
            int no = flowInstanceMapper.selectChangeHouseAndOwner(x.getId(), "base_house_info_update");
            BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.selectOwner(x.getId());
            int num = 0;
            if (null == baseOwnerInfo) {
                num = 0;
            } else {
                num = flowInstanceMapper.selectChangeHouseAndOwner(baseOwnerInfo.getId(), "base_owner_info_update");
            }
            if (no == 0 && num == 0) {
                x.setChange(NumStrEnum.ONE.getNum());
            } else {
                x.setChange(NumStrEnum.ZERO.getNum());
            }
            Map<String, Object> map = new HashMap(2);
            if ("已维护业主".equals(x.getState())) {
                // 计算应缴金额
                dueAmount = getDueAmount(x);
                if (dueAmount.compareTo(BigDecimal.ZERO) == 0) {
                    dueAmount = x.getFirstDue();
                    map.put("dueAmount", x.getFirstDue());
                } else {
                    //应缴金额
                    map.put("dueAmount", dueAmount);
                }
            } else {
                x.setFirstDue(BigDecimal.ZERO);
                map.put("dueAmount", 0);
            }
            //封装的 小区 实体
            map.put("house", x);
            mapList.add(map);
            pageAmount = pageAmount.add(dueAmount);
            if (null == pageBase.getStruArea()) {
                pageBase.setStruArea(BigDecimal.ZERO);
            }
            if (null == pageBase.getFirstDue()) {
                pageBase.setFirstDue(BigDecimal.ZERO);
            }
            if (null == pageBase.getFundBal()) {
                pageBase.setFundBal(BigDecimal.ZERO);
            }
            pageBase.setStruArea(pageBase.getStruArea().add(x.getStruArea()));
            pageBase.setFirstDue(pageBase.getFirstDue().add(x.getFirstDue()));
            pageBase.setFundBal(pageBase.getFundBal().add(x.getFundBal()));
        }
        //分页
        pageMap.put("dueAmount", pageAmount);
        pageMap.put("house", pageBase);
        mapList.add(pageMap);
        //总计
        List<BaseHouseInfo> listAll = baseHouseInfoMapper.findList(info);
        for (BaseHouseInfo x : listAll) {
            BigDecimal firstDue = BigDecimal.ZERO;
            if (null == baseAll.getStruArea()) {
                baseAll.setStruArea(BigDecimal.ZERO);
            }
            if (null == baseAll.getFirstDue()) {
                baseAll.setFirstDue(BigDecimal.ZERO);
            }
            if (null == baseAll.getFundBal()) {
                baseAll.setFundBal(BigDecimal.ZERO);
            }
            baseAll.setStruArea(baseAll.getStruArea().add(x.getStruArea()));
            baseAll.setFundBal(baseAll.getFundBal().add(x.getFundBal()));
            BigDecimal dueAmount;
            if (("1").equals(x.getOwnerState())) {
                if (("3").equals(x.getDueState())) {
                    dueAmount = getDueAmount(x);
                } else {
                    dueAmount = x.getFirstDue();
                }
                firstDue = x.getFirstDue();
            } else {
                dueAmount = BigDecimal.ZERO;
            }
            allAmount = allAmount.add(dueAmount);
            baseAll.setFirstDue(baseAll.getFirstDue().add(firstDue));
        }

        allMap.put("dueAmount", allAmount);
        allMap.put("house", baseAll);
        mapList.add(allMap);
        pageInfo.setList(mapList);
        return pageInfo;
    }

    /**
     * 交存维护
     *
     * @param id      缴存维护的ID
     * @param arcType 图档类型（逗号分隔）
     * @return 缴存维护记录
     */
    @Override
    public DepReqListInfo getInfoById(String id, String arcType) {
        DepReqListInfo depReqListInfo = depReqListInfoMapper.getInfo(id);
        DepReq depReq = depReqMapper.getInfo(depReqListInfo.getDepReqId());
        if (null!=depReq){
            depReqListInfo.setType(depReq.getType());
        }
        //看申请有效期
        String day = sysCoreParamMapper.getParamValueByCode(NumStrEnum.NINE.getNum());
        if (StringUtils.isNotBlank(day)) {
            int a = Integer.parseInt(day);
            depReqListInfo.setValidDate(DateUtils.getDate(a).toString());
        }
        if (null == depReqListInfo.getDeferAccr()) {
            depReqListInfo.setDeferAccr(BigDecimal.ZERO);
        }
        // 查询图档信息
        List<FileVO> fileVOList = fileService.getFileVOList(id, arcType);
        depReqListInfo.setFileTypeList(fileVOList);
        return depReqListInfo;
    }

    @Override
    public PageInfo<List<Map>> getHouseListByBuilIdsByDevelop(Page page, BaseHouseInfo b) {
        List<Map> mapList = new ArrayList<>();
        String[] ids = b.getId().split(",");
        //查看是否是同一个银行
        List<Integer> banks = baseBuildInfoMapper.selectByBankId(b.getId());
        if (banks.size() > 1) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), "选取的自然幢承办银行必须为同一个承办银行");
        }
        BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(ids[0]);
        BaseOrganization baseOrganization = baseOrganizationMapper.getInfo(baseBuildInfo.getDevelopNo());
        PageHelper.startPage(page.getPageNum(), page.getPageSize());
        List<BaseHouseInfo> list = baseHouseInfoMapper.getHouseListByBuilIdsdevelop(ids, b);
        PageInfo pageInfo = new PageInfo(list);
        for (BaseHouseInfo baseHouseInfo : list) {
            BigDecimal dueAmount = getDueAmount(baseHouseInfo);
            if (null == dueAmount) {
                dueAmount = BigDecimal.ZERO;
            }
            if (null==baseHouseInfo.getFirstDue()||(new BigDecimal(0)).compareTo(baseHouseInfo.getFirstDue())==0){
             baseHouseInfo.setDueAmount(dueAmount);
             baseHouseInfoMapper.updateFirstById(baseHouseInfo.getId(),dueAmount);
            }
            baseHouseInfo.setOwnerName(baseOrganization.getOrgName());
            int no = flowInstanceMapper.selectChangeHouseAndOwner(baseHouseInfo.getId(), "base_house_info_update");
            BaseOwnerInfo baseOwnerInfo = baseOwnerInfoMapper.selectOwner(baseHouseInfo.getId());
            if (no > 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "有在途审核的数据，请联系管理员");
            }
            if (null != baseOwnerInfo) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), baseHouseInfo.getHouseSite() + "有业主，无法进行补齐");
            }
            Map<String, Object> map = new HashMap(6);
            //封装的  实体
            map.put("house", baseHouseInfo);
            //应缴金额
                map.put("dueAmount", baseHouseInfo.getDueAmount());
                //自动填充 实付金额
                map.put("payAmount", baseHouseInfo.getDueAmount());
            mapList.add(map);
        }
        pageInfo.setList(mapList);
        return pageInfo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<String> submitSaveDepReqListInfos(List<DepReqListInfo> list) {
        String depReqId = UUIDUtil.getUUID();
        BaseHouseInfo infoOne = baseHouseInfoMapper.getInfo(list.get(0).getHouseId());
        BaseBuildInfo b = baseBuildInfoMapper.getInfo(infoOne.getBuildNo());
        BaseOrganization baseOrganization = baseOrganizationMapper.getInfo(b.getDevelopNo());
        BigDecimal dueAmount = new BigDecimal(0);
        //审核
        String flowState = flowAddAuditUtil.initFlow(depReqId, FlowTypeEnum.DEPOSIT_DEVELOP.getType(), null);
        for (DepReqListInfo info : list) {
            if (info == null) {
                return null;
            }
            BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(info.getHouseId());
            //房屋状态
            baseHouseInfoService.houseState(baseHouseInfo);
            int no = depReqListInfoMapper.selecthouseDep(info.getHouseId(), info.getOwnerNo());
            if (no > 0) {
                return null;
            }
            if (FlowTypeEnum.DEPOSIT.getType().equals(baseHouseInfo.getFlowInProgress())) {
                return null;
            }
            if (baseHouseInfo.getDueState().equals(NumStrEnum.ONE.getNum()) || baseHouseInfo.getDueState().equals(NumStrEnum.TWO.getNum())) {
                return null;
            }
            //添加业主信息
            String numOwner = baseOwnerInfoService.ownerNo(baseHouseInfo.getId());
            BaseOwnerInfo baseOwnerInfo = new BaseOwnerInfo();
            String ownerId = UUIDUtil.getUUID();
            baseOwnerInfo.setId(ownerId);
            baseOwnerInfo.setAccNo(baseHouseInfo.getId());
            baseOwnerInfo.setName(info.getOwnerName());
            baseOwnerInfo.setInfoType("0");
            baseOwnerInfo.setCreater(ShiroUserUtil.getUserName());
            baseOwnerInfo.setCreateTime(DateUtils.getNow());
            baseOwnerInfo.setIsAffiliated("0");
            baseOwnerInfo.setOwnerNo(numOwner);
            baseOwnerInfo.setState("1");
            BigDecimal bigDecimal = calculateAmount.calculateDueAmountDep(baseHouseInfo, null);
            dueAmount = dueAmount.add(bigDecimal);
            baseHouseInfo.setFirstDue(bigDecimal);
            // 添加房屋状态
            baseHouseInfo.setState("1");
            baseHouseInfo.setOwnerState("1");
            baseHouseInfo.setFlowInProgress(FlowTypeEnum.DEPOSIT_DEVELOP.getType());
            int num = baseHouseInfoMapper.update(baseHouseInfo);
            if (num == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
            //添加到dep_req_list 表
            info.setBuildId(baseHouseInfo.getBuildNo());
            info.setDepModeId(baseHouseInfo.getFirstMode());
            String id = UUIDUtil.getUUID();
            info.setId(id);
            info.setDepType("1");
            info.setCreater(ShiroUserUtil.getUserName());
            info.setPayAmount(info.getDueAmount());
            info.setOwnerNo(ownerId);
            info.setDepDate(DateUtils.getNow());
            info.setDepReqId(depReqId);
            //审核
            info.setFlowState(flowState);
            int change = baseOwnerInfoMapper.insert(baseOwnerInfo);
            if (change == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "添加业主信息操作失败");
            }
            info.setState(flowState != null && flowState.equals(NumStrEnum.TWO.getNum()) ? NumStrEnum.THREE.getNum() : NumStrEnum.ONE.getNum());
            num = depReqListInfoMapper.insert(info);
            if (num == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "添加缴存详情表操作失败");
            }
        }
        //添加dep_req表
        DepReq depReq = new DepReq();
        depReq.setId(depReqId);
        depReq.setDeferAccr(new BigDecimal(0));
        depReq.setBankCode(b.getBankCode());
        depReq.setCorpNo(b.getDevelopNo());
        depReq.setCorpType("01");
        depReq.setTotalNum(list.size());
        depReq.setDeferAccr(new BigDecimal(0));
        depReq.setReqOper(baseOrganization.getOrgName());
        depReq.setTotalAmount(dueAmount);
        depReq.setFundAmount(dueAmount);
        depReq.setReqDate(list.get(0).getDepDate());
        depReq.setStep("3");
        depReq.setType("1");
        depReq.setValidDate(list.get(0).getValidDate());
        depReq.setCreater(ShiroUserUtil.getUserName());
        depReq.setCreateTime(DateUtils.getNow());
        //审核
        if ((NumStrEnum.TWO.getNum()).equals(flowState)) {
            String no = DepositUtil.getNo(NumberEnum.ONE.getNum().toString());
            successDep(depReq, baseOrganization, b, dueAmount,no);
        } else {
            depReq.setState("0");
        }
        int count = depReqMapper.insert(depReq);
        List<String> lists=depReqListInfoMapper.selectAllIdByDepReq(depReqId);
        return lists;
    }

    /**
     * 企业补齐审核通过
     */
    @Override
    public DepReq successDep(DepReq depReq, BaseOrganization baseOrganization, BaseBuildInfo b, BigDecimal dueAmount,String no) {
        depReq.setNo(no);
        depReq.setState("1");
        AccKeepAccount accKeepAccount = new AccKeepAccount();
        accKeepAccount.setReqName(baseOrganization.getOrgName());
        accKeepAccount.setBusiNo(no);
        accKeepAccount.setBusiType("311");
        accKeepAccount.setCreateTime(DateUtils.getDateNow());
        accKeepAccount.setCreater(ShiroUserUtil.getUserName());
        accKeepAccount.setBankCode(b.getBankCode());
        accKeepAccount.setPayAmount(dueAmount);
        accKeepAccount.setAccountState(NumStrEnum.ZERO.getNum());
        accKeepAccount.setState(NumStrEnum.ONE.getNum());
        accKeepAccount.setSpecialAccount("325");
        accKeepAccount.setVaildDate("2999-12-12");
        accKeepAccount.setRegionId(b.getRegionNo());
        accKeepAccount.setGrantreqNum(depReq.getNo());
        BaseRegionInfo baseRegionInfo=baseRegionInfoMapper.getInfo(b.getRegionNo());
        accKeepAccount.setRemark(baseRegionInfo.getRegionName()+"缴存");
        int count = accKeepAccountMapper.insert(accKeepAccount);
        if (count == NumberEnum.ZERO.getNum()) {
            throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
        }
        return depReq;
    }

    /**
     * 审核
     *
     * @param opinion
     * @param id
     * @param mark
     * @return
     */
    @Override
    @Transactional
    public CommonResult addSubmit(String opinion, String id, String mark) {
        int i = NumberEnum.ONE.getNum();
        String auditState = flowAddAuditUtil.audit(id, opinion, mark,null);
        DepReq depReq = new DepReq();
        depReq.setId(id);
        //flow_state填写auditState
        //不在审核中则更新业务表
        if (null != auditState && !FlowStateEnum.IN_AUDIT.getState().equals(auditState)) {
            if (FlowStateEnum.PASS.getState().equals(auditState)) {
                DepReq d = depReqMapper.getInfo(id);
                List<DepReqListInfo> depReqLists = depReqListInfoMapper.getInfoByDepReqId(id);
                BaseOrganization baseOrganization = baseOrganizationMapper.getInfo(d.getCorpNo());
                BaseBuildInfo baseBuildInfo = baseBuildInfoMapper.getInfo(depReqLists.get(0).getBuildId());
                String no = DepositUtil.getNo(NumberEnum.ONE.getNum().toString());
                d.setNo(no);
                depReq = successDep(d, baseOrganization, baseBuildInfo, d.getTotalAmount(),no);
                int num = depReqMapper.succUpdate(depReq);
                if (num == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "生成申请编号失败");
                }
                num = depReqListInfoMapper.updateStateByDepReq(id, "3", "2");
                if (num == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改缴存申请表失败");
                }
            } else {
                String ownerId = depReqListInfoMapper.getDepByHouseId(id);
                int num = depReqListInfoMapper.updateStateByDepReq(id, "0", auditState);
                if (num == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改缴存申请表失败");
                }
                String houseIds = depReqListInfoMapper.getDepByHouseIds(id);
                num = baseHouseInfoMapper.updateOwnerStateAndPross(houseIds, "0", "0");
                if (num == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改房屋表失败");
                }
                num = baseOwnerInfoMapper.updatStateByOwnerNoAll("0", ownerId);
                if (num == 0) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), "修改业主表失败");
                }
            }
        }
        return CommonResult.ResponseResult(i);
    }

    /**
     * 缴存维护撤销  对于没绑定 申请的  直接删除了
     * 点击撤销之后修改状态为state=0
     *
     * @param depReqListInfoIds
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public CommonResult revocatDepReqList(String depReqListInfoIds) {
        CommonResult commonResult = CommonResult.ResponseResult(1);
        String[] ids = depReqListInfoIds.split(",");
        for (String id : ids) {
            if (!depReqListInfoMapper.getInfo(id).getState().equals(NumStrEnum.TWO.getNum())) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), "该数据已申请或撤销，请刷新页面重试");
            }
            var info = new DepReqListInfo();
            info.setId(id);
            info.setState(NumStrEnum.ZERO.getNum());
            DepReqListInfo d = depReqListInfoMapper.getInfo(id);
            BaseHouseInfo baseHouseInfo = baseHouseInfoMapper.getInfo(d.getHouseId());
            baseHouseInfo.setFlowInProgress(NumStrEnum.ZERO.getNum());
            int num = baseHouseInfoMapper.update(baseHouseInfo);
            if (num == 0) {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
            var ret = depReqListInfoMapper.update(info);
            if (ret > 0) {
                String uuid = UUIDUtil.getUUID();
                ret = depReqListInfoMapper.dep_revocatDoInsert(uuid, NumStrEnum.TWO.getNum(), id, ShiroUserUtil.getUserName(), DateUtils.getNow(), 1, null);
                if (ret < 1) {
                    throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
                }
                DepRevocatDetail depRevocatDetail = depositApplyService.revocationList(uuid, d);
                depReqListInfoMapper.dep_revocat_detailDdInsert(depRevocatDetail);
            } else {
                throw new CourseException(ShiroResultEnum.FAIL.getCode(), MessageEnum.FAIL.getMsg());
            }
        }
        return commonResult;
    }

}
